/**
 * @description 格式化时间
 * @param time
 * @param cFormat
 * @returns {string|null}
 */
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 表单刷新重置
 * @param {String} refName
 */
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields()
  }
}

/**
 * 添加日期范围
 * @param {Object} params
 * @param {Array} dateRange
 */
export function addDateRange(params, dateRange) {
  var search = params
  search.beginTime = ''
  search.endTime = ''
  if (null != dateRange && '' != dateRange) {
    search.beginTime = this.dateRange[0]
    search.endTime = this.dateRange[1]
  }
  return search
}

/**
 * @description 格式化时间
 * @param time
 * @param option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

/**
 * @description 将url请求参数转为json格式
 * @param url
 * @returns {{}|any}
 */
export function paramObj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"').replace(/\+/g, ' ') + '"}')
}

/**
 * @description 父子关系的数组转换成树形结构数据
 * @param data
 * @returns {*}
 */
export function translateDataToTree(data) {
  const parent = data.filter((value) => value.parentId === 'undefined' || value.parentId == null)
  const children = data.filter((value) => value.parentId !== 'undefined' && value.parentId != null)
  const translator = (parent, children) => {
    parent.forEach((parent) => {
      children.forEach((current, index) => {
        if (current.parentId === parent.id) {
          const temp = JSON.parse(JSON.stringify(children))
          temp.splice(index, 1)
          translator([current], temp)
          typeof parent.children !== 'undefined' ? parent.children.push(current) : (parent.children = [current])
        }
      })
    })
  }
  translator(parent, children)
  return parent
}

/**
 * @description 树形结构数据转换成父子关系的数组
 * @param data
 * @returns {[]}
 */
export function translateTreeToData(data) {
  const result = []
  data.forEach((item) => {
    const loop = (data) => {
      result.push({
        id: data.id,
        name: data.name,
        parentId: data.parentId,
      })
      const child = data.children
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i])
        }
      }
    }
    loop(item)
  })
  return result
}

/**
 * @description 10位时间戳转换
 * @param time
 * @returns {string}
 */
export function tenBitTimestamp(time) {
  const date = new Date(time * 1000)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '' + m : m
  let d = date.getDate()
  d = d < 10 ? '' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}

/**
 * @description 13位时间戳转换
 * @param time
 * @returns {string}
 */
export function thirteenBitTimestamp(time) {
  const date = new Date(time / 1)
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  m = m < 10 ? '' + m : m
  let d = date.getDate()
  d = d < 10 ? '' + d : d
  let h = date.getHours()
  h = h < 10 ? '0' + h : h
  let minute = date.getMinutes()
  let second = date.getSeconds()
  minute = minute < 10 ? '0' + minute : minute
  second = second < 10 ? '0' + second : second
  return y + '年' + m + '月' + d + '日 ' + h + ':' + minute + ':' + second //组合
}

/**
 * @description 获取随机id
 * @param length
 * @returns {string}
 */
export function uuid(length = 32) {
  const num = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += num.charAt(Math.floor(Math.random() * num.length))
  }
  return str
}

/**
 * @description m到n的随机数
 * @param m
 * @param n
 * @returns {number}
 */
export function random(m, n) {
  return Math.floor(Math.random() * (m - n) + n)
}

/**
 * @description addEventListener
 * @type {function(...[*]=)}
 */
export const on = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event && handler) {
      element.addEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * @description removeEventListener
 * @type {function(...[*]=)}
 */
export const off = (function () {
  return function (element, event, handler, useCapture = false) {
    if (element && event) {
      element.removeEventListener(event, handler, useCapture)
    }
  }
})()

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data, id, parentId, children, rootId) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId = rootId || 0
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  //循环所有项
  const treeData = cloneData.filter((father) => {
    let branchArr = cloneData.filter((child) => {
      //返回每一项的子级数组
      return father[id] === child[parentId]
    })
    branchArr.length > 0 ? (father.children = branchArr) : ''
    //返回第一层
    return father[parentId] === rootId
  })
  return treeData != '' ? treeData : data
}

// blob方式下载文件
export function download(res, filename) {
  let blob = new Blob([res])
  var a = document.createElement('a')
  var url = window.URL.createObjectURL(blob)
  a.href = url
  a.download = decodeURIComponent(filename)
  a.click()
  window.URL.revokeObjectURL(url)
}

// -------------------------- 正整数的正则表达式 ------------------------- //
export function expression(value) {
  var pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
  // 不符合正整数时
  if (!pattern.test(value)) {
    // input 框绑定的内容为空
    value = parseFloat(value)
  }
  return value
}

// -------------------------- 获取指定日期上一天、下一天 ------------------------- //
export function getNextDate(date, day) {
  var dd = new Date(date)
  dd.setDate(dd.getDate() + day)
  var y = dd.getFullYear()
  var m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1
  var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
  return y + '-' + m + '-' + d
}

// -------------------------- 基于只能输入数字与小数点情况下获取两位小数 ------------------------- //
export function parseNumber(values) {
  if (values.split('.')[1]) {
    return values.split('.')[1].length > 2
      ? parseFloat(values.split('.')[0] + '.' + values.split('.')[1].toString().slice(0, 2))
      : parseFloat(values.split('.')[0] + '.' + values.split('.')[1])
  } else {
    return values
  }
}

/**
 * 构造下拉选择型结构数据
 * @param {*} data 数据源
 * @param {*} label 展示字段
 * @param {*} value 实际值字段
 */
export function handleSelectOption(data, labelField, valueField) {
  const cloneData = JSON.parse(JSON.stringify(data))
  let result = []
  data.forEach((item) => {
    result.push({ label: item[labelField], value: item[valueField] })
  })
  return result
}

/**
 * 构造下拉选择型结构数据
 * @param {*} data 数据源
 * @param {*} label 展示字段
 * @param {*} value 实际值字段
 */
export function copyObject(data) {
  return JSON.parse(JSON.stringify(data))
}

/**
 * 获取单据状态
 * @param {*} key 状态值
 */
export function getDocStatus(key) {
  let status
  switch (key) {
    case '1':
      status = '已提交'
      break
    case '2':
      status = '已撤回'
      break
    case '3':
      status = '审核中'
      break
    case '4':
      status = '审核通过'
      break
    case '5':
      status = '审核不通过'
      break
    case '6':
      status = '已关闭'
      break
    default:
      // '0'
      status = '已保存'
      break
  }
  return status
}
/**
 * 判断是否为空或空串
 * @param {object} data
 */
function isEmpty(data) {
  return data == '' || data == null || data == undefined
}

/**
 * @description 计算两个时间并格式化
 * @param startTime
 * @param endTime
 * @returns {string}
 */
export function compoteFormatTime(startTime, endTime) {
  if (isEmpty(startTime) || isEmpty(endTime)) {
    return ''
  }
  let st = new Date(startTime)
  let et = new Date(endTime)
  let time = et.getTime() - st.getTime()
  return compoteFormatTimestamp(time)
  // 返回 几天 几时 几分 几秒
}

/**
 * @description 将时间戳格式化
 * @param timestamp
 * @returns {string}
 */
export function compoteFormatTimestamp(timestamp) {
  let result = ''
  // 时间差(秒)
  let time = timestamp / 1000
  const ds = 86400
  const hs = 3600
  const ms = 60
  // 向下取整数
  let day = parseInt(time / ds)
  let hours = parseInt((time - day * ds) / hs)
  let minute = parseInt((time - day * ds - hours * hs) / ms)
  let second = time - day * ds - hours * hs - minute * ms
  if (day != 0) {
    result += day + '天'
  }
  if (day != 0 || hours != 0) {
    result += hours + '时'
  }
  if (hours != 0 || minute != 0) {
    result += minute + '分'
  }
  result += second + '秒'
  return result
  // 返回 几天 几时 几分 几秒
}

/**
 * 表格合计项
 * @param {object} param
 */
export function getTableSummation(param) {
  const { columns, data } = param
  const sums = []
  const fields = ['price', 'number', 'amount']
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (fields.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          let prevV = new this.$Decimal(prev)
          let currV = new this.$Decimal(curr)
          const value = Number(curr)
          if (!isNaN(value)) {
            return prevV.add(currV).toNumber()
          } else {
            return new this.$Decimal(prev).toNumber()
          }
        }, 0)
      } else {
        sums[index] = ''
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}
